package com.lamerman;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.TreeMap;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.database.DataSetObserver;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;

public class FileDialog extends ListActivity {

	private static final String ITEM_KEY = "key";
	private static final String ITEM_IMAGE = "image";

	public static final String START_PATH = "START_PATH";
	public static final String RESULT_PATH = "RESULT_PATH";
	public static final String RESULT_EXT = "RESULT_EXT";
	public static final String ACTION_NAME = "ACTION_NAME";
	public static final String FILTER_EXTS = "FILTER_EXTS";

	private List<String> item = null;
	private List<String> path = null;
	private String root = "/";
	private TextView myPath;
	private EditText mFileName;
	private ArrayList<HashMap<String, Object>> mList;

	private Button cancelButton;
	private Button actionButton;
	private Button parentButton;
	private Spinner mSpinnerExts;

	private String parentPath;
	private String currentPath = root;
	private ArrayList<String> filterExts = null;
//	private String filterExt = null;

	private HashMap<String, Integer> lastPositions = new HashMap<String, Integer>();

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setResult(RESULT_CANCELED, getIntent());
		filterExts = getIntent().getStringArrayListExtra(FILTER_EXTS);
		setContentView(R.layout.file_dialog_main);
		mSpinnerExts = (Spinner) findViewById(R.id.fdSpinner);
		if (filterExts == null) {
			mSpinnerExts.setVisibility(Spinner.GONE);
		} else {
			ArrayAdapter<String> sa = new ArrayAdapter<String>(this, R.layout.extension_spinner_item, R.id.spinnerTarget, filterExts);
			sa.setDropDownViewResource(R.layout.extension_spinner_dropdown_item);
			mSpinnerExts.setAdapter(sa);
			mSpinnerExts.setOnItemSelectedListener(new OnItemSelectedListener() {

				@Override
				public void onItemSelected(AdapterView<?> parent, View view,
						int position, long id) {
					unselect();
					getDir(currentPath);
				}

				@Override
				public void onNothingSelected(AdapterView<?> parent) {
					// Do nothing
					
				}
			});
		}
		myPath = (TextView) findViewById(R.id.path);
		mFileName = (EditText) findViewById(R.id.fdEditTextFile);
		mFileName.addTextChangedListener(new TextWatcher(){

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				if (mFileName.getText().length() > 0) {
					actionButton.setEnabled(true);
				} else {
					actionButton.setEnabled(false);
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {}

			@Override
			public void afterTextChanged(Editable s) {}

		});

		parentButton = (Button) findViewById(R.id.buttonParent);
		parentButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (!currentPath.equals(root)) {
					unselect();                                                                                                                                                                                                             
					getDir(parentPath);
				}
			}
		});

		cancelButton = (Button) findViewById(R.id.fdButtonCancel);
		cancelButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				setResult(RESULT_CANCELED, getIntent());
				finish();
			}

		});
		actionButton = (Button) findViewById(R.id.fdButtonAction);
		String actionName = getIntent().getStringExtra(ACTION_NAME);
		if (actionName.length() > 0){
			actionButton.setText(actionName);
		}
		actionButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (mFileName.getText().length() > 0) {
					getIntent().putExtra(RESULT_PATH,
							currentPath + "/" + mFileName.getText());
					if (filterExts != null) {
						getIntent().putExtra(RESULT_EXT, mSpinnerExts.getSelectedItem().toString());
					}
					setResult(RESULT_OK, getIntent());
					finish();
				}
			}
		});
		actionButton.setEnabled(false);

		String startPath = getIntent().getStringExtra(START_PATH);
		if (startPath != null) {
			getDir(startPath);
		} else {
			getDir(root);
		}
	}



	private void getDir(String dirPath) {

		boolean useAutoSelection = dirPath.length() < currentPath.length();

		Integer position = lastPositions.get(parentPath);

		getDirImpl(dirPath);

		if (position != null && useAutoSelection) {
			getListView().setSelection(position);
		}

	}

	private void getDirImpl(String dirPath) {

		myPath.setText(getText(R.string.location) + ": " + dirPath);
		currentPath = dirPath;

		item = new ArrayList<String>();
		path = new ArrayList<String>();
		mList = new ArrayList<HashMap<String, Object>>();

		File f = new File(dirPath);
		File[] files = f.listFiles();

		if (dirPath.equals(root)) {
			parentButton.setEnabled(false);
		}
		else {
			parentButton.setEnabled(true);
			parentPath = f.getParent();
		}

		TreeMap<String, String> dirsMap = new TreeMap<String, String>();
		TreeMap<String, String> dirsPathMap = new TreeMap<String, String>();
		TreeMap<String, String> filesMap = new TreeMap<String, String>();
		TreeMap<String, String> filesPathMap = new TreeMap<String, String>();
		for (File file : files) {
			if (file.isDirectory()) {
				String dirName = file.getName();
				dirsMap.put(dirName, dirName);
				dirsPathMap.put(dirName, file.getPath());
			} else {
				if (fileRequired(file.getName())){
					filesMap.put(file.getName(), file.getName());
					filesPathMap.put(file.getName(), file.getPath());
				}
			}
		}
		item.addAll(dirsMap.tailMap("").values());
		item.addAll(filesMap.tailMap("").values());
		path.addAll(dirsPathMap.tailMap("").values());
		path.addAll(filesPathMap.tailMap("").values());

		SimpleAdapter fileList = new SimpleAdapter(this, mList,
				R.layout.file_dialog_row,
				new String[] { ITEM_KEY, ITEM_IMAGE }, new int[] {
				R.id.fdrowtext, R.id.fdrowimage });

		for (String dir : dirsMap.tailMap("").values()) {
			addItem(dir, R.drawable.folder);
		}

		for (String file : filesMap.tailMap("").values()) {
			addItem(file, R.drawable.file);
		}

		fileList.notifyDataSetChanged();

		setListAdapter(fileList);

	}

	private boolean fileRequired(String fileName) {
		if ((filterExts == null) || (mSpinnerExts.getSelectedItem().toString().equals("*"))) {
			return true;
		}
		int dot = fileName.lastIndexOf(".");
		if (dot == -1) {return false;}
		String ext = fileName.substring(dot+1, fileName.length());
		if (ext.equals(mSpinnerExts.getSelectedItem().toString())){
			return true;
		}
		else {
			return false;
 		}
	}



	private void addItem(String fileName, int imageId) {
		HashMap<String, Object> item = new HashMap<String, Object>();
		item.put(ITEM_KEY, fileName);
		item.put(ITEM_IMAGE, imageId);
		mList.add(item);
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {

		File file = new File(path.get(position));

		if (file.isDirectory()) {
			unselect();
			if (file.canRead()) {
				lastPositions.put(currentPath, position);
				getDir(path.get(position));
			} else {
				new AlertDialog.Builder(this).setIcon(R.drawable.icon)
				.setTitle(
						"[" + file.getName() + "] "
						+ getText(R.string.cant_read_folder))
						.setPositiveButton("OK",
								new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {

							}
						}).show();
			}
		} else {
			v.setSelected(true);
			mFileName.setText(file.getName());
			actionButton.setEnabled(true);
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if ((keyCode == KeyEvent.KEYCODE_BACK)) {
			unselect();

			if (!currentPath.equals(root)) {
				getDir(parentPath);
			} else {
				return super.onKeyDown(keyCode, event);
			}

			return true;
		} else {
			return super.onKeyDown(keyCode, event);
		}
	}

	private void unselect() {
		mFileName.setText("");
		actionButton.setEnabled(false);
	}
}